#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()


from celery import shared_task

from goods.models import GoodsModifyApplyment, LaunchedGoods
from merchants.models import MerchantMallApplyment


@shared_task
def automatic_audit_applyment(data):
    applyment_id = data['applyment_id']
    applyment = GoodsModifyApplyment.objects.get(id=applyment_id)
    if applyment.applyment_status != 1:
        return '申请单状态有误,请勿重复操作'
    goods = applyment.goods
    if applyment.applyment_type == 1:
        applyment.applyment_status = 2
        applyment.reject_reason = '自动审核'
        applyment.save()
        goods.remain_stock = goods.remain_stock + applyment.stock
        goods.is_launched = 1
        goods.save()
    else:
        applyment.applyment_status = 2
        applyment.reject_reason = '自动审核'
        applyment.save()
        goods.remain_stock = goods.remain_stock - applyment.stock
        goods.is_launched = 1
        goods.save()
        merchantenter_set = goods.merchant.merchantenter_set.all()
        for merchantenter in merchantenter_set:
            launchedgoods_data = {}
            launchedgoods_data['level_id'] = merchantenter.level_id
            launchedgoods_data['goods_id'] = goods.id
            launchedgoods_data['is_launched'] = 0
            launchedgoods_data['name'] = goods.name
            launchedgoods_data['category_id'] = 1
            launchedgoods_data['stock'] = 0
            LaunchedGoods.objects.get_or_create(defaults=launchedgoods_data, level_id=merchantenter.level_id, goods_id=goods.id)
    return '审核通过'


@shared_task
def automatic_audit_mall_applyment(data):
    applyment_id = data['applyment_id']
    applyment = MerchantMallApplyment.objects.get(id=applyment_id)
    merchant = applyment.merchant
    if applyment.applyment_state != 1:
        return '申请单状态有误,请勿重复操作'
    if applyment.applyment_type == 1:
        applyment.applyment_state = 2
        applyment.reject_reason = '自动审核'
        applyment.save()
        merchant.is_mall = 2
        merchant.save()
    return '审核通过'